package lt.ntec.danblog.server.core;

import com.google.appengine.api.users.UserService;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import lt.ntec.danblog.server.core.model.User;
import lt.ntec.danblog.server.core.model.UserDAO;
import lt.ntec.danblog.server.core.model.UserFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class GoogleUserManager implements UserManager {

    private static final Logger LOG = LoggerFactory.getLogger(
            GoogleUserManager.class);
    private UserDAO userDao;
    private UserService userService;
    private UserFactory userFactory;

    @Inject
    GoogleUserManager(UserDAO userDao, UserService userService,
                      UserFactory userFactory) {
        this.userDao = userDao;
        this.userService = userService;
        this.userFactory = userFactory;
    }

    @Override
    public User getCurrentUser() {
        if (!isAvailableValidUser()) {
            return null;
        }

        String email = userService.getCurrentUser().getEmail();
        try {
            User user = userDao.getUserByEmail(email);
            boolean userAdmin = userService.isUserAdmin();
            
            if (user.isAdmin() != userAdmin) {
                user.setAdmin(userAdmin);
                userDao.save(user);
            }
            
            return user;
            
        } catch (UserNotFoundException ex) {
            LOG.debug("Registering new user");
            Long userId = registerCurrentUser();
            return userDao.getById(userId);
        }
    }

    @Override
    public boolean isAvailableValidUser() {
        return userService.isUserLoggedIn();
    }

    @Override
    public User getUser(Long id) {
        return userDao.getById(id);
    }

    @Override
    public String getLoginUrl(String destination) {
        return userService.createLoginURL(destination);
    }

    @Override
    public String getLogoutUrl(String destination) {
        return userService.createLogoutURL(destination);
    }

    @Override
    public Long registerCurrentUser() {
        com.google.appengine.api.users.User currentUser =
                userService.getCurrentUser();
        boolean userAdmin = userService.isUserAdmin();
        User createUser = userFactory.createUser(currentUser, userAdmin);
        return userDao.save(createUser);
    }
}
